import redis from 'redis'
import { REDIS_CONF } from '../conf/db.js'

// 创建 redis 客户端
const redisClient = redis.createClient(REDIS_CONF.port, REDIS_CONF.host)

redisClient.on('error', (err) => {
	console.log(err)
})

function set(key, value) {
	if (value && typeof value === 'object') {
		value = JSON.stringify(value)
	}
	redisClient.set(key, value, redis.print)
}

function get(key) {
	return new Promise((resolve, reject) => {
		redisClient.get(key, (err, value) => {
			if (err) {
				return reject(err)
			}
			// resolve(value)
			if (value === null) {
				return resolve(null)
			}

			try {
				resolve(JSON.parse(value))
			} catch (ex) {
				resolve(value)
			}
		})
	})
}

export { set, get }
